<!-- 省市区三级选择器 -->
<template>
  <el-cascader
    ref="cascader"
    v-model="cityData"
    :props="cascaderProps"
  />
</template>
<script setup>
import { cityCode } from '@/api/common'
// leaf: 向下选择等级
const props = defineProps({
  // 数据
  modelValue: {
    type: Object,
    default: null
  },
  // 配置项
  options: {
    type: Object,
    default () {
      return {
        province: 'province', // 省
        city: 'city', // 市
        district: 'district', // 区
        provinceCode: 'provinceCode', // 省Code
        cityCode: 'cityCode', // 市Code
        districtCode: 'districtCode' // 区Code
      }
    }
  },
  leaf: {
    type: Number,
    default: 2
  }
})
const emit = defineEmits(['update:modelValue'])

const cascader = ref(null)
// 双向数据绑定数据修改
const { modelValue, options } = toRefs(props)

const cityData = computed({
  get () {
  // `province` varchar(32) DEFAULT '' COMMENT '省份',
  // `city` varchar(32) DEFAULT '' COMMENT '城市',
  // `district` varchar(32) DEFAULT '' COMMENT '区县',
    if (!modelValue.value) return []
    return [modelValue.value[options.value.provinceCode], modelValue.value[options.value.cityCode], modelValue.value[options.value.districtCode]]
  },
  set (val) {
    let obj = {}
    if (val) {
      const msg = cascader.value.getCheckedNodes()[0].pathLabels // 汉字

      obj[options.value.province] = msg[0]
      obj[options.value.city] = msg[1]
      obj[options.value.district] = msg[2]

      obj[options.value.provinceCode] = val[0]
      obj[options.value.cityCode] = val[1]
      obj[options.value.districtCode] = val[2]
    }
    emit('update:modelValue', obj)
    obj = {}
  }
})

const cascaderProps = {
  lazy: true,
  value: 'code',
  label: 'name',
  lazyLoad: async (node, resolve) => {
    const obj = {
      parentCode: node.value || 1
    }
    const data = await cityCode(obj)
    data.forEach((item) => {
      item.leaf = node.level >= props.leaf
    })
    resolve(data)
  }
}

//
// const change = () => {
//   emit('change', cascader.value.getCheckedNodes()[0])
// }
</script>

<style scoped lang='scss'>

</style>
